﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using XmlServer.ServiceContracts;
using XmlServer.ServiceImplementation;


namespace QuickReturnOperator
{
    public class QuickReturn : IOperator
    {

        // this is an example of a server that will return a response to the client right away,
        //  but is will create a thread to continue processing a long running request

        private string xmlRequest;

        public const string SERVER_NAME = "Quick Return Operator";
        public const string SERVER_VERSION = "1.0";

        public string Name
        {
            get { return SERVER_NAME; }
        }

        public string Version
        {
            get { return SERVER_VERSION; }
        }

        public string FullName
        {
            get { return String.Format("{0}_{1}", SERVER_NAME, Version); }
        }

        public string Description
        {
            get { return "This operator test running a long operation on a background thread and returning a success message to the client right away."; }
        }

        public List<IFact> Facts
        {
            get { return null; }
        }

        public IResponse ProcessRequest(IRequest request)
        {
            Response response = new Response();
            response.Request = request;     // return the original request object
            response.Success = true;        // assume a success

            try
            {

                // return the success response
                response.Facts = new List<IFact>()
                    {
                        new Fact {  Name = "Status", Value = "The request is currently being processed" }
                    };



                Thread t = new Thread(new ThreadStart(Process));
                t.Start();


            }
            catch (Exception ex)
            {
                response.Facts = XmlServer.Helper.Utilities.CreateException(ex);
                response.Success = false;
            }

            response.StopProcessing = System.Environment.TickCount;
            return response;

        }


        public void Process()
        {
            // sleep this thread for 15 seconds....
            // but the client should get the response right away...
            //    this might affect the server shutdown because this server is active

            var temp = this.xmlRequest;
            Thread.Sleep(15000);
        }
    }
}
